--
-- Author: shunguo.chen
-- Date: 2018-04-03 16:24:52
--
-- CosKOFHeadRender kof 选角色头像
--

local AvatarIconNode = require("app.widget.AvatarIconNode")

local ClassRef = app.mvc.createRenderClass(...)

--data =
function ClassRef.createWithData(data, node)
    local sprite = ClassRef.extend(node)
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end
function ClassRef.create(node)
    return ClassRef.createWithData(nil, node)
end

-- data = CosplayRole
function ClassRef:init(data)
    self.super.init(self, data)

    self._timeline = self:getTimeline()
    self._timeline:pause()

    self._ui.Panel_ami:setTouchEnabled(false)

    self._avatarIcon = AvatarIconNode.new(self._ui.Panel, "icon_img")

    self:refresh()
end

function ClassRef:refresh()
    self._ui.img:setVisible(self._data == nil)
    if self._data then
        self._avatarIcon:update(self._data:getAvatarParams())
    else
        self._avatarIcon:hide()
    end
end

function ClassRef:addTimeline(timeline)
    self._timeline = timeline
    self:runAction(timeline)
    timeline:pause()
end

function ClassRef:setIsEnemy(b)
    self._isEnemy = b
    self._ui.bg_foe:setVisible(b)
    self._ui.bg_team:setVisible(not b)
    self._ui.icon_img:setScaleX(b and -1 or 1)
end

function ClassRef:getWorldPosY()
    if not self._worldPosY then
        local worldPos = self:convertToWorldSpace(cc.p(0, 0))
        self._worldPosY = worldPos.y - 35
    end
    return self._worldPosY
end

function ClassRef:setTouchTip(tip, posX)
    self._ui.Panel:addTouchEventListener(function(sender, eventType)
        if not self._data then return end
        if eventType == ccui.TouchEventType.began then
            tip:setPosition(posX, self:getWorldPosY())
            tip:setData(self._data:getTipData())
            tip:setVisible(true)
        elseif eventType == ccui.TouchEventType.canceled or 
            eventType == ccui.TouchEventType.ended then
            tip:setVisible(false)
        end
    end)
end

function ClassRef:isSelected()
    return self._ui.selected:isVisible()
end

function ClassRef:setSelected(b)
    self._ui.selected:setVisible(b)
    if b then
        self._timeline:play("animation1", true)
    else
        self._timeline:pause()
    end
end

function ClassRef:playShowAction(data, cb)
    self:setSelected(false)
    self._ui.img:setVisible(false)
    self._timeline:play("animation2", false)
    self._timeline:setLastFrameCallFunc(function()
        executeFunc(cb)
    end)
    self:performWithDelay(function()
        self:setData(data)
    end, app:getAnimationInterval() * 20)
end

function ClassRef:onBtnClick(cb)
    self._onClick = cb
end

return ClassRef
